import re

from django.shortcuts import render
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.generics import CreateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import viewsets
from user.models import UserModel
from django10.utils.ronglianyun import send_message
from django.conf import settings
from user.serialize import Userseriali,CustomTokenObtainPairSerializer,RegisterSerializer
from user.serialize import generate_random_username
import random
class CreateUserViews(APIView):
    def get(self, request):
        UserModel.objects.create_user(username='root', email='123@123.com', password='789789', mobile="19137729317")
        return Response({'message': '添加用户信息成功'})
class MobileApiView(APIView):
    def get(self,request,mobile):
        try:
            UserModel.objects.get(mobile__exact=mobile)
            return Response({"message":"手机号已存在,请登录","code":400})
        except UserModel.DoesNotExist:
            if re.match(r"^1[3-9]\d{9}$", mobile):
                return Response({"message":"手机号可用","code":200},status=status.HTTP_200_OK)

                # return Response({"message":"手机号格式不正确","code":401},stats=status.HTTP_400_BAD_REQUEST)
# 发送短信验证
class SendSmsViews(APIView):
    def get(self, request, mobile):
        redis = get_redis_connection('sms_code')
        res_interval = redis.ttl(f'sms_{mobile}')
        if res_interval != -2:
            return Response({"message": f"短信发送过于频繁,请{res_interval}秒后重试"}, status=status.HTTP_400_BAD_REQUEST)
        rly = settings.RONG_LIAN_YUN
        tid = rly.get('reg_tid')
        sms_interval = rly.get('sms_interval')
        # 验证码失效时间
        sms_expire = rly.get('sms_expire')
        interval = sms_interval / 60
        code = f'{random.randint(0, 9999):04d}'
        datas = (code, interval)
        res = send_message(tid, mobile, datas)
        # 缓存事务
        pipe = redis.pipeline()
        pipe.multi()
        redis.setex(f'sms_{mobile}', sms_expire, code)
        redis.setex(f'interval_{mobile}', sms_interval, '-')
        pipe.execute()
        if res:
            return Response({'message': '短信发送成功...'}, status=status.HTTP_200_OK)
        else:
            return Response({'message': '短信发送失败',"code":404})
class LoginViews(APIView):
    def post(self, request):
        mobile =request.data.get('mobile')
        sms_code =request.data.get("smsCode")
        user = UserModel.objects.filter(mobile=mobile).first()
        if user:
            redis = get_redis_connection('sms_code')
            code = redis.get(f'sms_{mobile}')
            # redis中获取到数据类型,都是字节类型的
            print('redis中保存的短信验证码:', code)
            print(code.decode())
            print(sms_code)
            if code.decode() != sms_code:
                return Response({'message': '短信验证码错误...', "code": 403})
            else:
                token = CustomTokenObtainPairSerializer.get_token(user)
                return Response({'message': '登录成功...', "token": str(token), "code": 200}, status=status.HTTP_200_OK)
        else:
            # 注册并保存
            user = UserModel.objects.create_user(
                email = mobile + "@163.com",
                username=generate_random_username(6),
                mobile=mobile,
                password="123123",
                nikename=UserModel.generate_nikename(),
                avatar="avatar/1.jpg"
            )
            refresh = CustomTokenObtainPairSerializer.get_token(user=user)
            user.refresh = str(refresh)
            user.token = str(refresh.access_token)
            UserModel.save(user)
            return Response({'message': '注册成功...', "code": 201})



class UserinfoViews(viewsets.ModelViewSet):
    queryset = UserModel.objects.all()
    serializer_class = Userseriali
    @action(methods=['PUT'], detail=True)
    def update_nikename(self,request,pk):
        newnikename = request.data.get("nikename")
        user = UserModel.objects.get(id=pk)
        print("---------------------------------")
        print(newnikename)
        if user:
            user.nikename = newnikename
            user.save()
            return Response({"message":"修改成功","code":200})
        else:
            return Response({"message":"用户不存在","code":400})
# 注册视图
class RegisterView(CreateAPIView):
    queryset = UserModel.objects.all()
    serializer_class = RegisterSerializer


